package com.sxt.jwt.config;

import io.jsonwebtoken.SignatureException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.sxt.jwt.common.ReturnT;
 
@RestControllerAdvice
public class PermissionHandler {
	private String NullPointerExceptionStr="空指针异常";
    private String ArrayIndexOutOfBoundsStr="数组越界异常";
    private String ClassCastExceptionStr="类型转换异常";
    private String SignatureExceptionStr="Token为空";
    private int ERROR_CODE = 400;
	
    @ExceptionHandler(value = { SignatureException.class })
    @ResponseBody
    public ReturnT<?> authorizationException(SignatureException ex){
        return resultFormat(ERROR_CODE, new Exception(SignatureExceptionStr));
    }
    
  //空指针异常
    @ExceptionHandler(NullPointerException.class)
    public ReturnT<?> nullPointerExceptionHandler(NullPointerException ex) {
        return resultFormat(ERROR_CODE, new Exception(NullPointerExceptionStr));
    }

    //类型转换异常
    @ExceptionHandler(ClassCastException.class)
    public ReturnT<?> classCastExceptionHandler(ClassCastException ex) {
        return resultFormat(ERROR_CODE,  new Exception(ClassCastExceptionStr));
    }


    //数组越界异常
    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    public ReturnT<?> ArrayIndexOutOfBoundsException(ArrayIndexOutOfBoundsException ex) {
        return resultFormat(ERROR_CODE, new Exception(ArrayIndexOutOfBoundsStr));
    }

    //其他错误
    @ExceptionHandler({Exception.class})
    public ReturnT<?> exception(Exception ex) {
        return resultFormat(ERROR_CODE, new Exception());
    }
    
    private <T extends Throwable> ReturnT<String> resultFormat(Integer code, T ex) {
        ex.printStackTrace();
        return new ReturnT<String>(code, ex.getMessage());
    }
}
